<template>
	<div class="category">
		<div class="Function_bar">
			<el-button type="primary" style="margin: 10px 10px 10px 10px;" @click="addCategory">添加商品分类</el-button>
			<span>
				<el-input v-model=seacrch_category_name @input="seacrch_category_name = seacrch_category_name.trim()"
					style="width: 240px" placeholder="请输入一级分类名称" />
				<el-button type="primary" style="margin: 10px 10px 10px 10px;" @click="searchCategory()">查询商品分类</el-button>
				<el-button type="info" style="margin: 10px 10px 10px 10px;" @click="resolve()">重置</el-button>
			</span>
		</div>
		<el-table :data="categoryList" style="width: 100%" row-key="id" border>
			<el-table-column prop="category_name" label="分类名称" sortable />
			<el-table-column prop="status" label="状态" sortable>
				<template #default="scope">
					<el-switch v-model="scope.row.status" class="ml-2" inline-prompt
						style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="Y" inactive-text="N"
						@change="switchChange(scope.row)" />
				</template>
			</el-table-column>
			<el-table-column prop="level" label="类目等级">
				<template #default="scope">
					<div v-if="scope.row.level === '一级分类'" class="color-heart-circle"></div>
					<span v-else-if="scope.row.level === '二级分类'" class="color-heart-circle" style="background-color: blue"></span>
					<span v-else-if="scope.row.level === '三级分类'" class="color-heart-circle"
						style="background-color: green"></span>
					{{ scope.row.level }}
				</template>
			</el-table-column>
			<el-table-column prop="ctrl" label="操作">
				<template #default="scope" style="display: flex;">
					<div style="display: flex;">
						<el-button type="primary" round @click="editCategory(scope.row)">编辑</el-button>
						<el-popconfirm width="220" icon-color="#626AEF" title="你确认要删除该分类吗？">
							<template #reference>
								<el-button type="danger" round>删除</el-button>
							</template>
							<template #actions="{ confirm, cancel }">
								<el-button size="small" @click="cancel">取消</el-button>
								<el-button type="danger" size="small" @click="deleteCategory(scope.row)">
									确认！
								</el-button>
							</template>
						</el-popconfirm>
						<el-button type="success" round @click="addSCategory(scope.row)"
							v-if="scope.row.level !== '三级分类'">新增子类</el-button>
					</div>

				</template>
			</el-table-column>
		</el-table>
		<div style="display: flex; justify-content: flex-end; margin-top: 10px">
			<el-pagination v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize"
				:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="pageData.total"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
		<!-- 添加弹窗  -->
		<el-dialog v-model="dialogVisible" title="新增分类" width="50%">
			<el-form ref="userfrom" :model="fromData" :rules="rules">
				<el-form-item label="分类名称：" prop="category_name">
					<el-input v-model="fromData.category_name" placeholder="请输入分类名称" />
				</el-form-item>
				<el-form-item label="类目等级:" prop="level">
					一级分类
				</el-form-item>
				<el-radio-group v-model="fromData.status">
					<el-form-item label="状  态:" prop="status">
						<el-radio :value="true">Y</el-radio>
						<el-radio :value="false">N</el-radio>
					</el-form-item>
				</el-radio-group>
			</el-form>
			<template #footer>
				<div class="flex">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="sure(userfrom)">确定</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 编辑弹窗 -->
		<el-dialog v-model="dialogEVisible" title="编辑分类 " width="50%">
			<el-form ref="userfrom2" :model="fromData2" :rules="rules2">
				<el-form-item label="分类名称：" prop="category_name">
					<el-input v-model="fromData2.category_name" placeholder="请输入分类名称" />
				</el-form-item>
				<el-radio-group v-model="fromData2.status">
					<el-form-item label="状  态:" prop="status">
						<el-radio :value="true">Y</el-radio>
						<el-radio :value="false">N</el-radio>
					</el-form-item>
				</el-radio-group>
			</el-form>
			<template #footer>
				<div class="flex">
					<el-button @click="dialogEVisible = false">取消</el-button>
					<el-button type="primary" @click="sure2(userfrom2)">确定</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 新增子类弹窗 -->
		<el-dialog v-model="dialogSVisible" title="新增子类" width="50%">
			<el-form ref="userfrom3" :model="fromData3" :rules="rules3">
				<el-form-item label="分类名称：" prop="category_name">
					<el-input v-model="fromData3.category_name" placeholder="请输入分类名称" />
				</el-form-item>
				<el-form-item label="类目等级:" prop="level">
					{{ fromData3.level }}
				</el-form-item>
				<el-radio-group v-model="fromData3.status">
					<el-form-item label="状  态:" prop="status">
						<el-radio :value=true>Y</el-radio>
						<el-radio :value=false>N</el-radio>
					</el-form-item>
				</el-radio-group>
			</el-form>
			<template #footer>
				<div class="flex">
					<el-button @click="dialogSVisible = false">取消</el-button>
					<el-button type="primary" @click="sure3(userfrom3)">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>

</template>
<script setup>
import {
	ref,
	onMounted,
	reactive
} from "vue";
import {
	getCategoryApi,
	addCategoryApi,
	deleteCategoryApi,
	updateCategoryApi,
	searchCategoryApi,
} from "@/utils/api/category";
import {
	ElMessage
} from "element-plus";


// 商品列表
const categoryList = ref([]);
// 分页器
const pageData = ref({
	pageNum: 1,
	pageSize: 10,
	total: 0,
	currentPage: 1
});

// 初始化页数
function initPage() {
	pageData.value.pageNum = 1;
	pageData.value.currentPage = 1;
}

//添加分类
const fromData = reactive({
	category_name: "",
	status: true,
});
// 查询参数
const seacrch_category_name = ref("")

//弹窗隐藏
const dialogVisible = ref(false);
//rules 设置规则 
const rules = {
	category_name: [{
		required: true,
		message: "此项为必填项 ",
		trigger: "blur"
	}],
	status: [{
		required: true,
		message: "此项为必填项 ",
		trigger: "blur"
	}]
};

const userfrom = ref();
//新增确定键
const sure = (fromEl) => {
	fromEl.validate(res => {
		if (!res) {
			return fromData
		}
		//验证通过
		addCategoryApi(fromData).then(res => {
			//网络请求
			if (res.code === "200") {
				initPage()
				getCategory()
				fromData.category_name = "";
				fromData.status = true;
				ElMessage({
					message: '添加成功',
					type: 'success',
				})
			} else {
				ElMessage({
					message: res.message,
					type: 'error',
				})
			}
			dialogVisible.value = false;
		}).catch(error => {
			// 网络错误或服务器异常
			ElMessage({
				message: error.response?.data?.message || "网络异常，请稍后重试",
				type: "error",
			});
		});
	})
}

//编辑分类
const fromData2 = reactive({
	id: "",
	category_name: "",
	status: "",
});
const dialogEVisible = ref(false);


const rules2 = {
	category_name: [{
		required: true,
		message: "此项为必填项 ",
		trigger: "blur"
	}],
	status: [{
		required: true,
		message: "此项为必填项 ",
		trigger: "blur"
	}]
};
const userfrom2 = ref();

//编辑确认键
const sure2 = (fromEl) => {
	fromEl.validate(async res => {
		if (!res) {
			return fromData2
		}
		updateCategoryApi(fromData2).then(res => {
			if (res.code === "200") {
				initPage()
				getCategory()
				ElMessage({
					message: '编辑成功',
					type: 'success',
				})
			} else {
				ElMessage({
					message: res2.message,
					type: 'error',
				})
			}
			dialogEVisible.value = false;
		}
		).catch(error => {
			// 网络错误或服务器异常
			ElMessage({
				message: error.response?.data?.message || "网络异常，请稍后重试",
				type: "error",
			});
		});
	})


}

//新增子类

const fromData3 = reactive({
	category_name: "",
	parent_category_id: "",
	status: true,
	level: ""
});
//弹窗隐藏
const dialogSVisible = ref(false);

const rules3 = {
	category_name: [{
		required: true,
		message: "此项为必填项 ",
		trigger: "blur"
	}],
	status: [{
		required: true,
		message: "此项为必填项 ",
		trigger: "blur"
	}]
};
const userfrom3 = ref();

//新增子类确认键
const sure3 = (fromEl) => {
	//验证通过
	addCategoryApi(fromData3).then(res => {
		//网络请求
		if (res.code === "200") {
			initPage()
			getCategory()
			fromData3.category_name = "";
			fromData3.status = true;
			ElMessage({
				message: '添加成功',
				type: 'success',
			})

		} else {
			ElMessage({
				message: res.message,
				type: 'error',
			})
		}
		dialogSVisible.value = false;
	}).catch(error => {
		// 网络错误或服务器异常
		ElMessage({
			message: error.response?.data?.message || "网络异常，请稍后重试",
			type: "error",
		});
	});
}

// 初始化数据

onMounted(() => {
	getCategory();

})

//切换分页
const handleSizeChange = (val) => {
	pageData.value.pageSize = val;
	pageData.value.pageNum = 1;
	pageData.value.currentPage = 1;
	if (seacrch_category_name.value === '') {
		getCategory()
	} else {
		searchCategory()
	}

};

const handleCurrentChange = (val) => {
	pageData.value.currentPage = val;
	pageData.value.pageNum = val;
	if (seacrch_category_name.value === '') {
		getCategory()
	} else {
		searchCategory()
	}

};

// 获取分类列表
async function getCategory() {
	const res = await getCategoryApi(pageData.value);
	if (res.code === "200") {
		pageData.value.total = res.result.total;
		categoryList.value = setCategoryLevels(res.result.list, "一级分类");
	}
}
// 设置分类级别
function setCategoryLevels(categories, level) {
	return categories.map((item) => {
		const newItem = {
			...item,
			level: level, // 设置当前分类的级别
		};
		// 如果有 children，则递归处理
		if (item.children && item.children.length > 0) {
			newItem.children = setCategoryLevels(item.children, level === "一级分类" ? "二级分类" : "三级分类");
		}
		return newItem;
	});
}

// 切换状态
async function switchChange(row) {
	let date = {
		id: row.id,
		status: row.status,
		category_name: row.category_name,
	}
	const res = await updateCategoryApi(date);
	if (res.code === "200") {
		ElMessage({
			message: '切换状态成功',
			type: 'success',
		})
	} else {
		ElMessage({
			message: res.message,
			type: 'error',
		})
	}
}

//添加商品分类
async function addCategory(row) {
	dialogVisible.value = true;
}

// 查询商品分类
async function searchCategory() {
	if (seacrch_category_name.value === '' || seacrch_category_name.value === null) {
		ElMessage({
			message: '请输入一级分类名称',
			type: 'warning',
		});
		return
	}
	const data = {
		pageNum: pageData.value.pageNum,
		pageSize: pageData.value.pageSize,
		category_name: seacrch_category_name.value
	}
	console.log('data', data);
	const res = await searchCategoryApi(data)
	if (res.code === "200") {
		pageData.value.total = res.result.total;
		categoryList.value = setCategoryLevels(res.result.list, "一级分类");
	} else {
		ElMessage({
			message: res.result,
			type: 'success',
		});
	}
}

// 重置商品查询
async function resolve() {
	initPage()
	seacrch_category_name.value = ''
	getCategory()
}

//编辑
async function editCategory(row) {
	// console.log(row);
	dialogEVisible.value = true;
	const {
		category_name,
		status,
		id
	} = row;
	fromData2.category_name = category_name;
	fromData2.status = status;
	fromData2.id = id;
}

//新增子类
async function addSCategory(row) {
	dialogSVisible.value = true;
	console.log(row);

	const {
		id, level
	} = row;
	fromData3.parent_category_id = id;
	if (level === "一级分类") {
		fromData3.level = "二级分类";
	}
	if (level === "二级分类") {
		fromData3.level = "三级分类";
	}
}


//删除
async function deleteCategory(row) {
	try {
		const res = await deleteCategoryApi(row.id);
		ElMessage({
			message: '删除成功',
			type: 'success',
		});
		initPage();
		getCategory();
	} catch (err) {
		ElMessage({
			message: err.response.data.message,
			type: 'error',
		});
	}
}
</script>

<style lang="scss" scoped>
.category {
	width: 1280px;
	height: 100%;
	margin: 0 auto;
	background-color: #f2f2f2;
	padding: 20px;

	.Function_bar {
		display: flex;
		justify-content: space-between;
	}

	.color-heart-circle {
		width: 10px;
		/* 设置圆的直径 */
		height: 10px;
		background-color: red;
		/* 设置背景颜色为红色 */
		border-radius: 50%;
		/* 使其成为圆形 */
		display: inline-block;
		/* 使其成为行内块 */
	}
}
</style>